<template>
  <div class="passwordpage">
    <div class="formbox">
        <el-form :model="form" status-icon :rules="rules" ref="form" label-width="100px">
            <el-form-item label="旧密码" prop="old_password">
                <el-input type="password" v-model="form.old_password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="登录密码" prop="login_password">
                <el-input type="password" v-model="form.login_password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirm_password">
                <el-input type="password" v-model="form.confirm_password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('form')">保存</el-button>
            </el-form-item>
        </el-form>
    </div>
  </div>
</template>

<script>
import Api from '@/api'
import { logout } from '@/utils/auth'
export default {
    data() {
        var checkConfirmPassword = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.form.login_password) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }
        return {
            form: {

            },
            rules: {
                old_password: [
                    { required: true, message: '请输入旧密码', trigger: 'blur' },
                ],
                login_password: [
                    { required: true, message: '请输入登录密码', trigger: 'blur' },
                    { min: 5, max: 15, message: '长度在 5 到 16 个字符', trigger: 'blur' }
                ],
                confirm_password: [
                    { validator: checkConfirmPassword, trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        submitForm(form) {
            this.$refs[form].validate( async (valid) => {
                if (!valid) {
                    return false ;
                }
                const { data } = await Api.updateMyPwd(this.form)
                if (!data.success) {
                    return this.$message.error(data.msg)
                }
                // 清空个人信息，重新登录
                this.$message.success(data.msg)
                logout()

            })
        }
    }
}
</script>

<style lang="scss" scoped>
.formbox {
    width: 60%;
    min-width: 500px;
}
</style>